package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagedService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查看详细信息
     *
     * @param userId
     * @return
     */
    public UserInfo users(Long userId) {
        UserInfo user = userInfoApi.findById(userId);
        //判断是否被冻结
        if (redisTemplate.hasKey(Constants.FREEZE_USER + userId)) {
            user.setUserStatus("2");
        }
        return user;
    }

    /**
     * 查看视频列表
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    public PageResult videos(Integer page, Integer pagesize, Long uid) {
        //1.调用api分页查询视频列表
        PageResult pr = videoApi.videos(page, pagesize, uid);
        return pr;
    }

    /**
     * 查看动态列表
     *
     * @param page     页码
     * @param pagesize 条数
     * @param uid      用户id
     * @param skr      审核状态
     * @return
     */
    public PageResult messages(Integer page, Integer pagesize, Long uid, Integer skr) {
        //1.调用api查询动态列表
        PageResult pageResult = movementApi.messages(page, pagesize, uid, skr);
        //2.获取pageResult中的动态数据
        List<Movement> items = (List<Movement>) pageResult.getItems();
        //3.获取每一条动态的id
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        //4.获取每一个用户的详情
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds, null);
        //5.组装vo返回数据
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = infoMap.get(item.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, item);
                vos.add(vo);
            }
        }
        //6.把封装好的数据放回pageResult并返回
        pageResult.setItems(vos);
        return pageResult;
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage = userInfoApi.findAllUsers(page, pagesize);
        //获取用户详情集合
        List<UserInfo> list = iPage.getRecords();
        //遍历获取到每一个用户详情 判断是否被冻结
        for (UserInfo userInfo : list) {
            if (redisTemplate.hasKey(Constants.FREEZE_USER + userInfo.getId())) {
                userInfo.setUserStatus("2");
            }
        }
        return new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 用户冻结
     *
     * @param params
     * @return
     */
    public Map userFreeze(Map params) {
        //1.拼接key
        String userId = params.get("userId").toString();
        String key = Constants.FREEZE_USER + userId;
        //2.把冻结状态存到redis中
        //1为冻结3天，2为冻结7天，3为永久冻结
        String freezingTime = (String) params.get("freezingTime");
        String value = JSON.toJSONString(params);
        int days = 0;
        if (freezingTime.equals("1")) {
            days = 3;
        } else if (freezingTime.equals("2")) {
            days = 7;
        }
        if (days > 0) {
            redisTemplate.opsForValue().set(key, value, days, TimeUnit.MINUTES);
        }
        redisTemplate.opsForValue().set(key, value);

        //3.返回数据
        Map retMap = new HashMap();
        retMap.put("message", "冻结成功");
        return retMap;
    }

    /**
     * 解冻
     *
     * @param params
     * @return
     */
    public Map userUnFreeze(Map params) {
        //1.拼接key
        String userId = params.get("userId").toString();
        String key = Constants.FREEZE_USER + userId;
        //2.删除key
        redisTemplate.delete(key);
        //3.返回
        Map retMap = new HashMap();
        retMap.put("message", "解冻成功");
        return retMap;
    }

    /**
     * 查动态详情
     * @param movementId
     * @return
     */
    public MovementsVo findById(String movementId) {
        //1.调用api查询id为movementId的动态
        Movement movement = movementApi.findById(movementId);
        //2.根据动态数据获取用户详情
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());
        //3.封装vo返回
        MovementsVo vo = MovementsVo.init(userInfo, movement);
        return vo;
    }
}
